package com.coursehub.course.repository;

import com.coursehub.course.entity.Chapter;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 章节仓库接口
 * 
 * @author CourseHub Team
 */
@Repository
public interface ChapterRepository extends JpaRepository<Chapter, Long> {
    
    /**
     * 根据课程ID查找章节，按顺序排序
     */
    @Query("SELECT c FROM Chapter c WHERE c.course.id = :courseId ORDER BY c.orderIndex ASC")
    List<Chapter> findByCourseIdOrderByOrderIndex(@Param("courseId") Long courseId);
    
    /**
     * 根据课程ID和章节类型查找章节
     */
    @Query("SELECT c FROM Chapter c WHERE c.course.id = :courseId AND c.type = :type ORDER BY c.orderIndex ASC")
    List<Chapter> findByCourseIdAndType(@Param("courseId") Long courseId, @Param("type") Chapter.ChapterType type);
    
    /**
     * 统计课程的章节数量
     */
    @Query("SELECT COUNT(c) FROM Chapter c WHERE c.course.id = :courseId")
    Long countByCourseId(@Param("courseId") Long courseId);
    
    /**
     * 获取课程中最大的章节顺序号
     */
    @Query("SELECT MAX(c.orderIndex) FROM Chapter c WHERE c.course.id = :courseId")
    Integer findMaxOrderIndexByCourseId(@Param("courseId") Long courseId);
    
    /**
     * 检查课程中是否存在指定顺序的章节
     */
    @Query("SELECT COUNT(c) > 0 FROM Chapter c WHERE c.course.id = :courseId AND c.orderIndex = :orderIndex")
    boolean existsByCourseIdAndOrderIndex(@Param("courseId") Long courseId, @Param("orderIndex") Integer orderIndex);
    
    /**
     * 根据课程ID删除所有章节
     */
    void deleteByCourseId(Long courseId);
    
    /**
     * 查找免费章节
     */
    @Query("SELECT c FROM Chapter c WHERE c.course.id = :courseId AND c.isFree = true ORDER BY c.orderIndex ASC")
    List<Chapter> findFreeByCourseId(@Param("courseId") Long courseId);
}